package net.daum.webtoon.android;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import net.daum.webtoon.android.jibx.XMLBinder;
import net.daum.webtoon.android.jibx.data.Item;
import net.daum.webtoon.android.jibx.data.Rss;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ContentListActivity extends Activity {

	public static String TAG = ContentListActivity.class.getSimpleName();
	private ListView mView;
	private final String TOONRSS = "http://cartoon.media.daum.net/webtoon/rss/";
	private final String TOONDOMAIN = "http://cartoon.media.daum.net/";
	public static final String TOONNAME = "TOONNAME";
	public static int mSeleIdx;
//	public static final String TOONNAME = "TOONNAME";
//	public static final String TOONNAME = "TOONNAME";
	private static ArrayList<Item> mItem;
	Handler gBaseHandler = new Handler();
	private static String mToonName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list);

		mView = (ListView) findViewById(R.id.main_list);

		if (!getIntent().getBooleanExtra("GETNEXT", false)) {
			mToonName = getIntent().getStringExtra(TOONNAME);

			if (mToonName != null && !mToonName.isEmpty())
				new Thread(new Runnable() {

					@Override
					public void run() {
						HttpURLConnection conn = null;
						InputStream in = null;
						FileOutputStream out = null;

						try {
							conn = (HttpURLConnection) new URL(TOONRSS + mToonName).openConnection();
							conn.setConnectTimeout(5000);
							conn.setReadTimeout(5000);

							if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
								in = conn.getInputStream();
//							Log.d(TAG, pinpToStr(in));
								Rss rss = (Rss) XMLBinder.unmarshalling(conn.getInputStream(), Rss.class);
								mItem = rss.getChannel().getItems();
							}

							conn.disconnect();

						} catch (Exception e) {
							Log.e(TAG, e.toString());
						} finally {
							if (mItem != null) {
								Log.d(TAG, mItem.size() + "");

								for (Item lItem : mItem)
									downLoadThumb(lItem.getDescription().split("'")[1]);

								gBaseHandler.post(new Runnable() {

									@Override
									public void run() {

										mView.setAdapter(new WebToonListAdapter(getApplicationContext(), mItem));
									}
								});
							}
						}

					}
				}, TAG).start();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		if (getIntent().getBooleanExtra("GETNEXT", false)) {
			if (mSeleIdx > 0) {
				mSeleIdx--;
				String[] passName = mItem.get(mSeleIdx).getGuid().trim().split("/");
				startActivity(new Intent(ContentListActivity.this, MainActivity2.class).putExtra(ContentListActivity.TOONNAME,
						passName[passName.length - 1]));
			} else if (mSeleIdx == 0) {
				Toast.makeText(getApplicationContext(), "@@@@@@@@@@", 1000);
				startActivity(new Intent(ContentListActivity.this, WebToonListActivity.class));
			}
		}
		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	private class WebToonListAdapter extends ArrayAdapter<Item> {

		public WebToonListAdapter(Context context, ArrayList<Item> aLis) {
			super(context, R.layout.content_item, aLis);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			ViewWrapper wrapper = null;

			if (row == null) {
				row = getLayoutInflater().inflate(R.layout.content_item, null);
				wrapper = new ViewWrapper(row);
				row.setTag(wrapper);
			} else
				wrapper = (ViewWrapper) row.getTag();

			final Item info = mItem.get(position);
			final int idx = position;
			wrapper.getBase().setBackgroundColor((position % 2) == 0 ? android.R.color.background_dark : android.R.color.background_light);
			wrapper.getThumbImgage().setImageBitmap(getBitmapDrawable(info.getDescription().split("'")[1]));
			wrapper.getSubTitle().setText(info.getTitle());

			row.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					mSeleIdx = idx;
					String[] passName = info.getGuid().trim().split("/");
					startActivity(new Intent(ContentListActivity.this, MainActivity2.class).putExtra(ContentListActivity.TOONNAME,
							passName[passName.length - 1]));
				}
			});
			return row;
		}

		private class ViewWrapper {
			private View mmmBase;
//			private TextView numOfContent;
			private TextView mmmSubTitle;
			private ImageView mmmthumb;

			public ViewWrapper(View base) {
				mmmBase = base;
			}

			public View getBase() {
				return mmmBase;
			}

			public ImageView getThumbImgage() {
				if (mmmthumb == null) {
					mmmthumb = (ImageView) mmmBase.findViewById(R.id.thumb);
//					mmmthumb.setSelected(true);
				}
				return mmmthumb;
			}

//			public TextView getNumofContent() {
//				if (numOfContent == null) {
//					numOfContent = (TextView) mmmBase.findViewById(R.id.numOfContent);
//					numOfContent.setSelected(true);
//				}
//				return numOfContent;
//			}

			public TextView getSubTitle() {
				if (mmmSubTitle == null) {
					mmmSubTitle = (TextView) mmmBase.findViewById(R.id.subtitle);
					mmmSubTitle.setSelected(true);
				}
				return mmmSubTitle;
			}
		}

	}

	public void downLoadThumb(final String url) {
		try {

			String lFileName = makeFileName(url);

			String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + getApplicationContext().getPackageName()
					+ "/temp";

			File lTempFile = new File(path, lFileName);
			if (lTempFile.exists())
				return;

			URL lurl = new URL(url);
			URLConnection conn = lurl.openConnection();
			conn.connect();
			BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
			final Bitmap bm = BitmapFactory.decodeStream(bis);
			bis.close();

			saveFile(bm, lFileName);

		} catch (IOException e) {
			Log.e(TAG, e.toString());
		}
	}

	public Bitmap getBitmapDrawable(String aUrl) {
		File lTempFile = null;
		String fileName = makeFileName(aUrl);
		String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + getApplicationContext().getPackageName()
				+ "/temp";

		String extState = Environment.getExternalStorageState();

		if (extState.equals(Environment.MEDIA_MOUNTED)) {
			File lPath = new File(path);
			if (!lPath.exists())
				lPath.mkdirs();

			lTempFile = new File(path, fileName);
			if (lTempFile.exists())
				return BitmapFactory.decodeFile(lTempFile.getAbsolutePath());
		}

		return BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
	}

	private String makeFileName(String aUrl) {
		String[] returnStrs = aUrl.split("/");
		return returnStrs[returnStrs.length - 1];
	}

	private void saveFile(Bitmap bitmap, String fileName) {
		File lTempFile = null;

		String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + getApplicationContext().getPackageName()
				+ "/temp";

		String extState = Environment.getExternalStorageState();

		if (extState.equals(Environment.MEDIA_MOUNTED)) {
			File lPath = new File(path);
			if (!lPath.exists())
				lPath.mkdirs();

			lTempFile = new File(path, fileName);

			FileOutputStream out;

			try {
				out = new FileOutputStream(lTempFile);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

	}

	public String pinpToStr(InputStream inputStream) {

		StringBuffer out = new StringBuffer();
		try {

			byte[] buffer = new byte[4094];
			for (int n; (n = inputStream.read(buffer)) != -1;) {
				String lkj = new String(buffer, 0, n);
				Log.d(TAG, lkj);
				out.append(lkj);

			}
		} catch (Exception e) {

		}

		return out.toString();
	}
}
